package it.eng.get.pdfwe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;



/**
 * @author <div style="width: 100%; height: 2em;
 * background-repeat: repeat-x; 
 * background-image: url(http://www.mysoftworks.net/images/author_back.gif);" >
 * <a style="float: right; font-size: .9em; margin: 1.2em .5em .1em .1em; color: #658A16; color: 658A16; font-family: helvetica; font-weight: bold; text-decoration: none" href="http://www.mysoftworks.net">
 * Antonio Giovannetti for Engineering</a>
 * </div>
 */
/**
 * @author <div style="width: 100%; height: 2em;
 * background-repeat: repeat-x; 
 * background-image: url(http://www.mysoftworks.net/images/author_back.gif);" >
 * <a style="float: right; font-size: .9em; margin: 1.2em .5em .1em .1em; color: #658A16; color: 658A16; font-family: helvetica; font-weight: bold; text-decoration: none" href="http://www.mysoftworks.net">
 * Antonio Giovannetti for Engineering</a>
 * </div>
 * E' necessario iText 2.0.8
 */
public class FlyingSaucerHtmlToPdfWriter implements PDFGenerator {

	
	private String rawHtml;
	
	public FlyingSaucerHtmlToPdfWriter(String rawHtml) {
		this.rawHtml = rawHtml;
	}
	

	public byte[] generatePdf()  {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ITextRenderer renderer = new ITextRenderer();
		Tidy t2 = new Tidy();
		t2.setMakeClean(true);
		t2.setXHTML(true);
		t2.setXmlSpace(true);
		t2.setDocType("omit");
		t2.setNumEntities(true);
		t2.setTidyMark(false);
		t2.setHideEndTags(false);
		PDFWeUtils.tidyParse(t2, new ByteArrayInputStream(rawHtml.getBytes()), baos);
		try {
//			renderer.setDocumentFromString(baos.toString());
			renderer.layout();
			renderer.createPDF(baos); //new PDF is created from the input .xhtml
			baos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return PDFWeUtils.getPDFError(e);
		} 
	}

}
